package com.cr.crsystem.system.controller;

import com.cr.crsystem.common.config.ZnwdConfig;
import com.cr.crsystem.common.utils.Result;
import com.cr.crsystem.system.service.impl.ZnwdServiceImpl;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okhttp3.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 *    智能问答
 */
@CrossOrigin
@Api(tags = "智能问答")
@Slf4j
@RestController
@RequestMapping("/system/znwd")
public class ZnwdController {
    @Autowired
    private ZnwdServiceImpl znwdService;
    @Autowired
    private ZnwdConfig znwdConfig;

    public static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    // 客服功能
    @GetMapping("/kefu")
    public Result<String> kefu(@RequestParam("message") String message) throws IOException {
        // 封装提问消息
        try {
            String messageAfterDeal = znwdService.question(message);
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType,messageAfterDeal);
            Request request = new Request.Builder()
                    .url(znwdConfig.getUrl() + znwdConfig.getAccessToken())
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            return Result.OK(znwdService.getResult(response));
        } catch (IOException e) {
            return Result.OK("客服处理失败，请重新提问");
        }
    }
}
